package be.msec.client.utils;

import java.math.BigInteger;

public class TextOperations {
	private final static String nullString = "null";

	public final static String hexChars[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };

	public static byte stringCharToBCDByte(String data, int pos) {
		return (byte) (Integer.parseInt(data.substring(pos, pos + 2), 16));
	}

	public static String hexDump(BigInteger big) {
		return hexDump(big.toByteArray());
	}

	public static String hexDump(byte[] data) {
		if(data!=null)
			return hexDump(data, 0, data.length);
		else return "";
	}

	public static String hexDump(byte[] data, int length) {
		return hexDump(data, 0, length);
	}

	public static String hexDump(byte[] data, int offset, int length) {
		String result = "";
		String part = "";
		for (int i = 0; i < MathOperations.min(data.length, length); i++) {
			part = ""
					+ hexChars[(byte) (MathOperations.unsignedInt(data[offset + i]) / 16)]
					+ hexChars[(byte) (MathOperations.unsignedInt(data[offset + i]) % 16)];
			result = result /*+ "(byte)"*/+ part/*+", "*/;
		}
		return result;
	}

	final static public int tagLen = 1;

	public static int getTagIdentifier(byte[] data, int pos) {
		return data[pos];
	}

	public static int getDataLen(byte[] data, int pos) {
		int i = 0;
		int len = 0;
		while (MathOperations.unsignedInt(data[pos + i]) == 255) {
			len = len * 255 + 255;
			i++;
		}
		len += MathOperations.unsignedInt(data[pos + i]);
		return len;
	}

	public static int getLenLen(byte[] data, int pos) {
		int i = 0;
		while (MathOperations.unsignedInt(data[pos + i]) == 255) {
			i++;
		}
		return i + 1;
	}

	public static String getString(byte[] data, int pos, int len){
		return new String(data, pos, len);
	}

	public static byte[] selectBytes(byte[] data, int pos, int len){
		byte[] res = new byte[len];
		for (int i = 0; i < len; i++)
			res[i] = data[pos + i];
		return res;
	}

}
